<?php
class App_Module_Media_Component_Image_Ctrl_Http_Web extends Mozg_Controller_Instance
{
    private $_imageInfo = array();
    
    protected function ControllerInit ()
    {

    }
    
    protected function PrimaryActionInit ($basicActionName)
    {
     
    }

    public function PrAction()
    {
        $this->analysePr();
    }

    public function analysePrAction()
    {
        list($requestUri) = explode('?', Mozg::Request('http')->getRequestUri());
        $filePath = ltrim($requestUri, '/');
        $pathParts = pathinfo($filePath);

        if (0 !== strpos($filePath, _CACHE_FOLDER_THUMB) ||
            !Mozg::Lib('Dir')->TestExtension($filePath, Mozg_Cfg::Get('global')->GetMediaFilesExtensions()))
        {
            throw new Mozg_Exception_NotFound();
        }

        $imageFolder = substr($pathParts['dirname'], strlen(_CACHE_FOLDER_THUMB));
        list($thumbFolder, $imageFolder) = explode('/', $imageFolder, 2);
        $originalFilePath = _ROOT_PATH.$imageFolder. '/' .$pathParts['basename'];
        
        $imageFileObj = Mozg::Lib('image')->GetImage($originalFilePath);
        
        $mapper = Mozg_Mapper::Get('Image');
        
        if (!$mapper->IsThumbFolder($thumbFolder) || !$imageFileObj->IsImage())
        {
            throw new Mozg_Exception_NotFound();
        }

        $thumbPath = _ROOT_PATH.$mapper->GetImageThumbFolder($thumbFolder, $imageFolder);

        if (!Mozg::Lib('dir')->Create($thumbPath))
        {
            throw new Mozg_Exception_NotFound();
        }
        
        $folderSize = $mapper->GetThumbFolderSizes($thumbFolder);
		$imageFileObj->Resize($thumbPath, $pathParts['basename'], $folderSize['size'], false, false, $folderSize['saveProportions'], $folderSize['watermark']);
		
		if ($imageFileObj->IsError())
		{
            throw new Mozg_Exception_NotFound();
		}

		$info = getimagesize($thumbPath.$pathParts['basename']);
		$info['filesize'] = filesize($thumbPath.$pathParts['basename']);
		$this->SetImageInfo($info);
		
		Mozg::Layout('media')->SetTemplate('Image');
		Mozg::SubAction()->Set('imageInfo', array($this, 'GetImageInfo'));
		
		Mozg::Response('http')->TurnCompression(false);
        Mozg::Response('http')->SetBody(file_get_contents($thumbPath.$pathParts['basename']));
    }
    
    private function SetImageInfo($info)
    {
        $this->_imageInfo = $info;
    }

    public function GetImageInfo()
    {
        return $this->_imageInfo;
    }
}